//
//  LGDownloadManager.m
//  LGNetworkDemo
//
//  Created by dangwc on 2019/5/15.
//  Copyright © 2019 dangwc. All rights reserved.
//

#import "LGDownloadManager.h"
#import "LGNetworkingManager.h"
#import "LGDownloadBuffer.h"
#import <CommonCrypto/CommonDigest.h>

//资源下载历史数据缓存
static NSString *const SourceHistoryData = @"SourceHistoryData";    //可以自定义

@interface LGDownloadManager()

@property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask;

@property (nonatomic,assign) TSDownloadMode downloadMode;

@property (nonatomic,copy) NSString  *filePath;

@property (nonatomic,copy) NSString  *requestUrl;

@end

@implementation LGDownloadManager



-(instancetype)initWithDownloadModel:(TSDownloadMode)downloadMode{
    if (self = [super init]) {
        _downloadMode = downloadMode;
    }
    return self;
}


-(void)downloadDataWithRequestUrl:(NSString *)requestUrl
                        filesPath:(NSString *)localFilesPath
                           fileID:(NSString *)fileID
                         progress:(void (^)(double))downloadProgressBlock
                          seccess:(void (^)(NSURL *))seccess
                          failure:(void (^)(NSError *))failure{
    
    self.requestUrl = requestUrl;
    //防止中文乱码
    requestUrl = [requestUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrl]];
    
    //判断资源列表中有没有该资源
    NSString *filePath = [localFilesPath stringByAppendingPathComponent:fileID];
    if ([self isfileExistsAtPath:filePath]) {
        seccess([NSURL fileURLWithPath:filePath]);
    }else{
        //获取缓存数据
        NSData *resumeData = [self getResumeDataWithUrl:requestUrl];
        self.downloadTask = nil;
        if (resumeData) {
            self.downloadTask = [[LGNetworkingManager shareNetworking] downloadTaskWithResumeData:resumeData progress:^(NSProgress * _Nonnull downloadProgress) {
                downloadProgressBlock(downloadProgress.fractionCompleted);
            } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                NSString *path = [localFilesPath stringByAppendingPathComponent:response.suggestedFilename];
                return [NSURL fileURLWithPath:path];
            } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                if (error) {
                    failure(error);
                }else{
                    //删除缓存列表数据
                    NSMutableDictionary *resumeDic = [LGDownloadBuffer getCachesDictionaryDataForTableName:SourceHistoryData].mutableCopy;
                    [resumeDic removeObjectForKey:[self md5WithString:self.requestUrl]];
                    [LGDownloadBuffer saveCachesWithTableName:SourceHistoryData cachesDataDictionary:resumeDic.copy];
                    seccess(filePath);
                }
            }];
            
        }else{
            
            self.downloadTask = [[LGNetworkingManager shareNetworking] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                
                downloadProgressBlock(downloadProgress.fractionCompleted);
                
            } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                
                NSString *path = [localFilesPath stringByAppendingPathComponent:response.suggestedFilename];
                return [NSURL fileURLWithPath:path];
                
            } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                if (error) {
                    failure(error);
                }else{
                    seccess(filePath);
                }
            }];
        }
    }
    [self.downloadTask resume];
}

-(void)resumeDownload{
    [self.downloadTask resume];
}


-(void)cancelDownload{
    if (self.downloadTask) {
        NSString *fileMd5Name = [self md5WithString:self.requestUrl];
        [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            if (resumeData) {
                NSMutableDictionary *resumeDic = [LGDownloadBuffer getCachesDictionaryDataForTableName:SourceHistoryData].mutableCopy;
                if (!resumeDic) {
                    resumeDic = [NSMutableDictionary dictionary];
                }
                [resumeDic setObject:resumeData forKey:fileMd5Name];
                [LGDownloadBuffer saveCachesWithTableName:SourceHistoryData cachesDataDictionary:resumeDic];
            }
        }];
        self.downloadTask = nil;
    }
}

-(void)suspendDownload{
    
    [self.downloadTask suspend];
}

#pragma mark - helpMethod

-(NSData *)getResumeDataWithUrl:(NSString *)url{
    
    if (url.length < 1) {
        return  nil;
    }
    //从缓存列表中获取数据
    NSString *resumeName = [self md5WithString:url];
    NSData *resumeData = [LGDownloadBuffer getCachesValueForTableName:SourceHistoryData forKey:resumeName];
    return resumeData;
}


-(BOOL)isfileExistsAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
        return YES;
    }else {
        return NO;
    }
}

-(NSString *)md5WithString:(NSString *)string{
    
    const char *cStrValue = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStrValue, (CC_LONG)strlen(cStrValue), result);
    NSMutableString *ciphertext = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSUInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [ciphertext appendFormat:@"%02x", result[i]];
    }
    return ciphertext;
}

@end
